package com.chao.controller;

import com.chao.controller.viewobject.UserVO;
import com.chao.error.BusinessException;
import com.chao.error.EnumError;
import com.chao.response.CommonReturnType;
import com.chao.service.UserService;
import com.chao.service.model.UserModel;
import com.chao.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @GetMapping("/id")
    public CommonReturnType findUserById(Integer id){
        UserVO user = userService.getUserById(id);
        return new CommonReturnType(user);
    }

    @RequestMapping("/register")
    public CommonReturnType register(String telephone, String code, String name, Integer gender, Integer age, String password) throws BusinessException {
        String otpCode = (String) httpServletRequest.getSession().getAttribute(telephone);
        if(!com.alibaba.druid.util.StringUtils.equals(code, otpCode)){
            throw new BusinessException(EnumError.PARAMETER_VALIDATION_ERROR,"验证码不正确");
        }
        UserModel model = new UserModel();
        model.setTelephone(telephone);
        model.setName(name);
        model.setGender(gender.byteValue());
        model.setAge(age);
        model.setRegisterMode("byphone");
        model.setEncryptPassword(CommonUtils.md5(password));

        System.out.println(model);

        userService.register(model);
        return new CommonReturnType(null);
    }

}
